package com.jiuxian.scheduling.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;

/**
 * Created by wangjingqing on 2017/12/25.
 */
public class DataSourceUtil {

    static Logger logger = LoggerFactory.getLogger(DataSourceUtil.class);

    static Connection connection;
    static {
        init();
    }


    private static void  init(){
        try {
            Class.forName("org.hsqldb.jdbcDriver");
            connection = DriverManager.getConnection("jdbc:hsqldb:file:/data/sheduling/table;create=true;ifexists=false","sa","");
            Runtime.getRuntime().addShutdownHook(new Thread(()->{
                try {
                    if(!connection.isClosed()){
                        connection.close();
                    }
                } catch (Exception e) {
                    logger.error("关闭数据库异常：",e);
                }
            }));
        } catch (Exception e) {
            logger.error("数据连接异常：",e);
        }
    }
    public static Connection getConnection(){
        if(connection == null){
            init();
        }
        return connection;
    }
    /**
     * 获取Statement<br>
     * @return Statement
     */
    public static Statement getStatement(){
        if(connection == null){
            return null;
        }
        try {
            connection.createStatement();
        } catch (SQLException e) {
            logger.error("获取Statement 异常：",e);
        }
        return null;
    }

    public static void main(String[] args) {
        try {
            ResultSet rs = connection.getMetaData().getTables(null,null,"",null);
            System.out.println(rs.next());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
